package com.hopital5.zhangyz.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogRecordAspect {
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    // 定义切点Pointcut
    @Pointcut("execution(* com.iyoukeji.epic.product.controller.*Controller.*(..))")
    public void execController() {
    }

    @Around("execController()")
    public Object doAroundController(ProceedingJoinPoint pjp) throws Throwable {
        return log(pjp);
    }

    private Object log(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        logger.info("请求开始 " + pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName());
        logger.info("请求各个参数, url: {}, method: {}, uri: {}, queryString: {}, args: {}", url, method, uri, queryString, mapper.writeValueAsString(pjp.getArgs()));

        Object result = pjp.proceed();

        logger.debug("请求结束，controller的返回值是 " + mapper.writeValueAsString(result));
        return result;
    }

}